package webs.servlet.ServletContext;
//下载文件

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@WebServlet("/servletContext_test")
public class ServletContext_test extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        //1.获取文件名
        String fileName=req.getParameter("filename");
        //2.通过文件名获取文件绝对路径
        ServletContext context=this.getServletContext();
        String path=context.getRealPath("/img/"+fileName);
        //3.通过字节流将数据关联，即将文件加载进内存
        FileInputStream inputStream=new FileInputStream(path);

        //4.获取文件类型，设置响应头。文件格式及打开方式
        String mimeType=context.getMimeType(fileName);
        resp.setHeader("content-type",mimeType);
        resp.setHeader("content-disposition","attachement;filename="+fileName);//fileName是下载提示框的内容

        //5.将数据写到输出流
        OutputStream outputStream=resp.getOutputStream();
        byte[] buffer=new byte[1024*8];
        int length=0;
        while((length=inputStream.read(buffer))!=-1)
        {
            outputStream.write(buffer,0,length);
        }
        outputStream.close();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        this.doPost(req,resp);
    }
}
